package edu.fudan.jwxt.controller;

import edu.fudan.jwxt.common.ResultBody;
import edu.fudan.jwxt.service.CourseService;
import edu.fudan.jwxt.service.CourseTimeService;
import edu.fudan.jwxt.service.CourseTimeVOService;
import edu.fudan.jwxt.service.TeacherCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/courses")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @Autowired
    private CourseTimeService courseTimeService;

    @Autowired
    private TeacherCourseService teacherCourseService;

    // 查看所有courses,包含所有coursedto


    /*
    // 查看所有courses,包含所有coursedto
    @GetMapping
    public ResultBody CourseListAll(){
        //CheckUserAdmin();
        List<Course> courses=courseService.list();
        List<CourseDto> transfer = courseService.Transfer(courses);
        for (CourseDto courseDto: transfer){
            List<Pair<Integer, Integer>> timeByCourse = courseTimeVOService.getTimeByCourse(courseDto.getCourseId());
            List<Pair<Integer, List<Integer>>> pairs = TimeUtils.specificTimeToArrayTime(timeByCourse);
            courseDto.setSpecifiedTime(pairs);
            courseDto.setCourseTime(TimeUtils.specificTimeToTime(courseTimeVOService.getTimeByCourse(courseDto.getCourseId())));
            if (courseDto.getSpecifiedTime() != null){
                courseDto.setHours(String.valueOf(timeByCourse.size()));
            }else{
                courseDto.setHours("0");
            }
        }
        return ResultBody.success(transfer);
    }

    @GetMapping("/major/{majorId}")
    public ResultBody CourseByMajorId(@PathVariable int majorId){
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Course::getMajorId,majorId);
        List<Course> courses=courseService.list(queryWrapper);

        List<CourseDto> transfer = courseService.Transfer(courses);
        for (CourseDto courseDto: transfer){
            List<Pair<Integer, Integer>> timeByCourse = courseTimeVOService.getTimeByCourse(courseDto.getCourseId());
            List<Pair<Integer, List<Integer>>> pairs = TimeUtils.specificTimeToArrayTime(timeByCourse);
            courseDto.setSpecifiedTime(pairs);
            courseDto.setCourseTime(TimeUtils.specificTimeToTime(courseTimeVOService.getTimeByCourse(courseDto.getCourseId())));
            if (courseDto.getSpecifiedTime() != null){
                courseDto.setHours(String.valueOf(timeByCourse.size()));
            }else{
                courseDto.setHours("0");
            }
        }
        return ResultBody.success(transfer);
    }

    // 处理请求
    @GetMapping("/Requests/Deal/{Ans}/{Choice}")
    public ResultBody DealWithRequests(@PathVariable int Ans,@PathVariable Integer Choice){
        //CheckUserAdmin();
        boolean BoolAns=(Ans != 0);
        courseTeacherRequestService.dealWithApplications(BoolAns,Choice);
        return ResultBody.success();
    }

    @PostMapping("/Requests/Deal/1")
    public ResultBody DealWithRequestList(@RequestBody List<Integer> list){
        for (Integer i: list){
            courseTeacherRequestService.dealWithApplications(true,i);
        }
        return ResultBody.success();
    }

    // 查询教师课程
    @GetMapping("/{uid}")
    public ResultBody teacherCourses(@PathVariable String uid){
        //CheckUserUID(uid);
        List<Course> courses=courseService.selectByFirstString("teacher_id",uid);
        List<CourseDto> transfer = courseService.Transfer(courses);
        for (CourseDto courseDto: transfer){
            List<Pair<Integer, Integer>> timeByCourse = courseTimeVOService.getTimeByCourse(courseDto.getCourseId());
            List<Pair<Integer, List<Integer>>> pairs = TimeUtils.specificTimeToArrayTime(timeByCourse);
            courseDto.setSpecifiedTime(pairs);
            courseDto.setCourseTime(TimeUtils.specificTimeToTime(courseTimeVOService.getTimeByCourse(courseDto.getCourseId())));
            if (courseDto.getSpecifiedTime() != null){
                courseDto.setHours(String.valueOf(timeByCourse.size()));
            }else{
                courseDto.setHours("0");
            }
        }
        return ResultBody.success(transfer);
    }

    // 获取对应学院课程信息
    @GetMapping("/colleges/{college_id}")
    public ResultBody collegeCourses(@PathVariable String college_id){
        List<Course> courses=courseService.selectByFirstString("college_id",college_id);
        return ResultBody.success(courseService.Transfer(courses));
    }

    // 单个添加课程
    @PostMapping("/insert")
    public ResultBody Insert(@RequestBody Course course){
        CheckUserAdmin();
        courseService.checkRoomTimeOccupy(course);
        List<Pair<Integer, Integer>> list = TimeUtils.exactClassTimeToSpecificTime(course.getExactClassTime());
        course.setCourseId(course.getCourseNumbering());
        if (list != null){
            course.setHours(String.valueOf(list.size()));
        }else{
            course.setHours("0");
        }
        course.setCourseTime(TimeUtils.specificTimeToTime(list));
        boolean flag=courseService.save(course);
        if (flag && list != null && !list.isEmpty()){
            courseTimeVOService.saveTimeByCourse(course.getCourseId(), list);
        }
        return ControllerUtils.JudgeByFlag(flag,Constants.CODE_600,"课程序号已存在");

    }

    // 单个删除课程
    @PostMapping("/delete")
    public ResultBody Delete(@RequestBody String course_id){
        //CheckUserAdmin();
        //System.out.println(course_id);
        boolean flag= courseService.removeById(course_id);
        return ControllerUtils.JudgeByFlag(flag,Constants.CODE_600,"删除课程主键不存在");
    }

    // 单个课程修改
    @PostMapping("/update")
    public ResultBody Update(@RequestBody Course course){
        CheckUserAdmin();
        courseService.checkRoomTimeOccupy(course);
        List<Pair<Integer, Integer>> list = TimeUtils.exactClassTimeToSpecificTime(course.getExactClassTime());
        course.setCourseId(course.getCourseNumbering());
        if (list != null){
            course.setHours(String.valueOf(list.size()));
        }else{
            course.setHours("0");
        }
        course.setCourseTime(TimeUtils.specificTimeToTime(list));
        boolean flag=courseService.updateById(course);
        if (flag && list != null && !list.isEmpty()){
            courseTimeVOService.saveTimeByCourse(course.getCourseId(), list);
        }
        return ControllerUtils.JudgeByFlag(flag,Constants.CODE_600,"更新课程主键不存在");
    }

    // 查看教师所有申请
    @GetMapping("/TeacherRequests")
    public ResultBody TeacherRequestListAll(){
        //CheckUserAdmin();
        List<CourseTeacherRequest> templist= courseTeacherRequestService.list();
        List<CourseTeacherRequestDto> transfer = courseTeacherRequestService.Transfer(templist);
        return ResultBody.success(transfer);
    }

    // 教师添加请求
    @PostMapping("/TeacherRequests/Add")
    public ResultBody TeacherRequest(@RequestBody CourseTeacherRequest courseTeacherRequest){
        CheckUserTeacher();
        if (!courseTeacherRequest.getExactClassTime().isEmpty()){
            courseTeacherRequest.setExactClassTimeString(TimeUtils.exactClassTimeToExactClassTimeString(courseTeacherRequest.getExactClassTime()));
        }
        if (!courseTeacherRequest.getOperation().equals("delete")){
            courseService.checkRoomTimeOccupy(new Course(courseTeacherRequest));
        }
        List<String> exactClassTime = courseTeacherRequest.getExactClassTime();
        if (exactClassTime != null && !exactClassTime.isEmpty() && !exactClassTime.get(0).equals("")){
            courseTeacherRequest.setExactClassTimeString(TimeUtils.exactClassTimeToExactClassTimeString(exactClassTime));
            courseTeacherRequest.setCourseTime(TimeUtils.specificTimeToTime(TimeUtils.exactClassTimeToSpecificTime(exactClassTime)));
            courseTeacherRequest.setHours(String.valueOf(exactClassTime.size()));
        }
        courseTeacherRequest.setCourseId(courseTeacherRequest.getCourseNumbering());
        Course byId = courseService.getById(courseTeacherRequest.getCourseId());
        if (byId != null && courseTeacherRequest.getOperation().equals("insert")){
            return ResultBody.error("400", "课程序号已存在");
        }
        String courseId = courseTeacherRequest.getCourseId();
        LambdaQueryWrapper<CourseTeacherRequest> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseTeacherRequest::getCourseId, courseId);
        List<CourseTeacherRequest> list = courseTeacherRequestService.list(lambdaQueryWrapper);
        if (list != null && !list.isEmpty()){
            return ResultBody.error("400", "当前课程正有等待审批的申请");
        }
        courseTeacherRequestService.save(courseTeacherRequest);
        return ResultBody.success();
    }

    // TODO: 2022/4/9  
    @PostMapping("/insert/csv")
    public ResultBody AddExcel(MultipartFile file) throws IOException {
        //CheckUserAdmin();
        //加载文件
        InputStream inputStream = file.getInputStream();
        InputStreamReader ir = new InputStreamReader(inputStream);

        CsvReader reader = CsvUtil.getReader();
        List<CourseTeacherRequest> courses = reader.read(ir,CourseTeacherRequest.class);

        //添加用户
        Map<String,Object> map = courseService.saveCsv(courses);

        return ResultBody.success(map);
    }

    @PostMapping("major/{majorId}")
    public ResultBody SearchByMajorId(@PathVariable Integer majorId){
        return ResultBody.success(courseService.selectByFirstString("major_id",majorId));
    }


    @GetMapping("/trial")
    public String Trial(){
        return "Successfully connected!";
    }

    @GetMapping("/enableselect")
    public ResultBody getEnableSelectCourse(){
        return ResultBody.success(DataConfig.enableSelectCourse);
    }

    @PutMapping("/enableselect")
    public ResultBody setEnableSelectCourse(){
        DataConfig.enableSelectCourse = !DataConfig.enableSelectCourse;
        return ResultBody.success(DataConfig.enableSelectCourse);
    }

     */
}


